//
//  CZUserStatusViewModel.swift
//  weibo27
//
//  Created by mac on 16/4/18.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import Foundation
import SDWebImage
// MARK: 处理微博的网络方法 让model与控制器不直接打交道
class CZUserStatusViewModel {
    
    lazy var statusList = [CZStatusViewModel]()
}

extension CZUserStatusViewModel{

    func loadUserStatus(isPullup isPullup:Bool, finished:(isSuccess:Bool)->()){
        
        //下拉刷新  取出数组中第一条数据的id
        let since_id = isPullup ? 0 : (statusList.first?.userStatus.id ?? 0)
        //上拉刷新  取出数组中最后一条条数据的id
        let max_id = isPullup ? (statusList.last?.userStatus.id ?? 0) : 0
        
        NetTools.shareTools.loadStatus(since_id: since_id, max_id: max_id) { (result, error) -> () in
            
            if error != nil{
                print("加载数据失败")
                finished(isSuccess: false)
                return
            }
            
            //获取数据 获取数组任何AnyObject在使用的时候就要先进行转换一下
            guard let array = result?["statuses"] as? [[String: AnyObject]] else{
                finished(isSuccess: false)
                print("数据的格式有误")
                return
            }
            
            //1 定义一个可变的数组
            var arrayM = [CZStatusViewModel]()
            
            //2 遍历数组
            for dict in array{
                
                arrayM.append(CZStatusViewModel(userStatus: CZUserStatus(dict: dict)))
            }
            
            print("一共刷新\(arrayM.count)条数据")
            
            if max_id>0{
                self.statusList += arrayM
            }else{
                //3 给全局的遍历赋值
                self.statusList = arrayM + self.statusList
            }
            // 4调用单张图片的下载
            self.singleImageDown(arrayM,finished: finished)
            
        }
    }
    // MARK: 调用单张图片的下载
    private func singleImageDown(statusList: [CZStatusViewModel],finished:(isSuccess:Bool)->()){
        
        // 创建调度组
        let group = dispatch_group_create()
        
        // 遍历数组
        for vm in statusList{
            
            if vm.thumbnail_pic?.count != 1{
                continue
            }
           
            //获取url
            let url = vm.thumbnail_pic![0]
//             print("开始缓存图像 \(url)")
            //1 使用SD下载图片 入组的操作
            dispatch_group_enter(group)
            
            SDWebImageManager.sharedManager().downloadImageWithURL(url,
                options: [],
                progress: nil,
                completed: { (image, _, _, _, _) -> Void in
                    
                    // 2单张图片下载完成  出租
                    dispatch_group_leave(group)
            })
        }
        //3 监听调度组的完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
//            print("图片的缓存完成")
            
            //完成后的回调
            finished(isSuccess: true)
        }
    }
}





























